<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\AdminAuth;
use App\Models\Admin\AdminMenu;
use App\Models\Admin\AdminProduct;
use App\Models\Admin\AdminRegion;
use App\Models\Admin\Balance;
use App\Models\Admin\Company;
use App\Models\Admin\CompanyData;
use App\Models\Admin\CompanyType;
use App\Models\Admin\CustomerServiceAgent;
use App\Models\Admin\CustomerServiceRole;
use App\Models\Admin\Document;
use App\Models\Admin\Member;
use App\Models\Admin\MemberAddress;
use App\Models\Admin\MemberInfo;
use App\Models\Admin\Menu;
use App\Models\Admin\MenuAuth;
use App\Models\Admin\PartnerSetting;
use App\Models\Admin\Setting;
use App\Models\Admin\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Carbon\Carbon;

class CompanyController extends AdminController
{
    use AdminTrait;

    public $m_company;
    public $m_menu;
    protected $connection;

    public function __construct(Company $m_company,Menu $m_menu)
    {
        parent::__construct();
        $this->m_company=$m_company;
        $this->m_menu=$m_menu;
        $this->connection = DB::connection('old_mysql');
    }

    //获取客户列表
    public function list(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $this->vali_rules['model']='exists:company_type,id';
        $this->vali_rules['company_name']='filled|string';
        $this->vali_rules['domain_name']='filled|string';
        $this->vali_rules['name']='filled|string';
        $this->vali_rules['mobile']='filled|numeric';
        $this->vali_rules['email']='filled|string';
        $this->vali_rules['start_time']='filled';
        $this->vali_rules['end_time']='filled';
        $this->vali_rules['province_id']='filled|integer';
        $this->vali_rules['city_id']='filled|integer';
        $this->vali_rules['county_id']='filled|integer';
        $validator = Validator::make($input, $this->vali_rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
//        获取分页配置
        $this->getPageAndSize($input);
        //DB::beginTransaction();
        try {
            /*$list=Company::getList($input,$this->skip,$this->size);
            $count=Company::getCount($input);*/
            $data=Company::getList($input,$this->skip,$this->size);
            //DB::commit();
            return $this->success($data);
        }
        catch (\Exception $exception)
        {
            //DB::rollBack();
            return $this->error(['-1',$exception->getMessage()]);
        }
    }

    //获取客户列表,不分页
    public function getAllCompany(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rules=[
          'model'=>  'required|exists:company_type,id'
        ];
        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        try {
            $list=Company::getListAll($input['model']);
            $data=[
                'list'=>$list,
            ];
            return $this->success($data);
        }
        catch (\Exception $exception)
        {
            return $this->error();
        }
    }


    //获取客户详情
    public function getCompanyDetail(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rules=[
          'id'=>'required|integer|min:1|exists:company,id'
        ];
        $this->vali_msg['id.exists']='客户不存在';
        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        $info=Company::getDetail($id);
        $region_id=$info->base_address;
        //获取省市区数据
        $path_list=AdminRegion::getPathListById($region_id);
        $active_pid=AdminRegion::getPathById($region_id);
        array_unshift($active_pid,$region_id);
        $info['active_pid']=array_reverse($active_pid);
        $info['path_list']=$path_list;
        return $this->success($info);
    }

    //根据客户id，获取管理员列表
    public function administratorByComId(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'company_id'=>'required|exists:company,id'
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $input['role_id']=1;
        $admin_list=User::getList($input);
        return $this->success(['list'=>$admin_list]);
    }

    //修改客户的超级管理员密码
    public function changePasswordComAdmin(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'user_id'=>'required|exists:users,id',
            'password'=>'required',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $user_id=$input['user_id'];
        DB::beginTransaction();
        try {
            $password=Hash::make($input['password']);
            $info=User::find($user_id);
            $perInfo = $info->getOriginal();//获取修改之前的字段
            $info->password=$password;
            $info->save();
            $nextInfo = $info->getChanges();//获取修改之后的字段
            User::addLog($perInfo,$nextInfo,6,__FUNCTION__);
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }

    }

    //免密登陆
    public function loginCompanyNoPass(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'user_id'=>'required|exists:users,id',
            'company_id'=>'required|exists:company,id',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $user_id=$input['user_id'];
        $company_id=$input['company_id'];
        $user=User::where('company_id',$company_id)->where('id',$user_id)->first();
        if(!$user)  return $this->error(['-1','管理员不存在']);
        $com_info=Company::select('id','company_name','domain_name','model')->find($company_id);
        if(!$com_info->domain_name) return$this->error(['-1','客户未设置域名']);
        $token=Auth::guard('company')->login($user,true);
        if(!$token) return $this->error(['-1','token获取失败']);
        //记录日志
        Company::addLog($com_info->getOriginal(),[],6,__FUNCTION__);
        $domain_name_arr=explode(',',$com_info->domain_name);
        $rout='';
        switch ($com_info->model)
        {
            case 1:
                $rout='padmin';
                break;
            case 2:
            case 3:
                $rout='cadmin';
                break;
        }

        $url='http://'.$domain_name_arr[0].'/'.$rout;
        return $this->success([
            'url'=>$url,
            'token'=>'Bearer ' .$token,
        ]);
    }

    //新增客户
    public function addCompany(BaseRequest $request)
    {
        $input=$request->only('cust_id','product_ids','renewal_money','remark','company_name','company_fullname','name','mobile','email','address','start_time','end_time','domain_name','model','bind_dispatch','status','base_address','long_lati','commission_rate','open_reduction','salesman','contract','voucher');
        $rules=[
            'company_name'=>'required|string',
            'company_fullname'=>'required|string',
            'name'=>'required|string',
            'mobile'=>'required|digits:11',
            'email'=>'email',
            'address'=>'required|string',
            'status'=>'required|in:0,1',
            'start_time'=>'required|integer',
            'end_time'=>'required|gt:start_time',
            'domain_name'=>'required|string',
            'model'=>'required|exists:company_type,id',
            'bind_dispatch'=>[
                'integer'
            ],
            'base_address'=>'required|integer',
            'long_lati'=>'required|string',
            'commission_rate'=>'required_unless:model,3|integer',
            'renewal_money'=>'required_if:model,3|numeric',
            'open_reduction'=>'required|in:0,1',
        ];
        $this->vali_msg['end_time.gt']='结束时间必须大于开始时间';
        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $res_co=Company::where('company_name',$input['company_name'])->count();
        if($res_co)
        {
            return $this->error(['60001',config('errorcode.60001')]);
        }
        if(!empty($input['bind_dispatch']))
        {
            $where=[
                'id'=>$input['bind_dispatch'],
                'model'=>1,
            ];
            $res_co=Company::where($where)->count();
            if(!$res_co)
                return $this->error(['60002',config('errorcode.60002')]);
        }
        //判断域名唯一
//        域名转数组
        $domain_arr=explode(',',$input['domain_name']);
        foreach ($domain_arr as $v)
        {
            $info = Company::whereRaw("FIND_IN_SET('".$v."',domain_name)")->count();
            if($info)
            {
                return $this->error(['60003','域名已存在']);
            }
        }
        $open_reduction=$input['open_reduction'];
        DB::beginTransaction();
        try {
            $cust_id=$input['cust_id']??0;
            //unset($input['cust_id']);
            $input['commission_rate']=isset($input['commission_rate'])?$input['commission_rate'].'‰':'';
            $input['email']=$input['email']??'';
            unset($input['open_reduction']);
            $input['audit'] = 0;
            $m_info=Company::create($input);
            $id=$m_info->id;
            if (method_exists($this->m_company,'addLog')){
                $this->m_company->addLog($m_info,[],1);
            }
            //添加客服
            if($cust_id)
            {
                /*$company_ids=CustomerServiceAgent::where('id',$cust_id)->value('company_ids');
                if($company_ids)
                {
                    $company_ids_arr=explode(',',$company_ids);
                    $company_ids_arr[]=$id;
                }
                else
                    $company_ids_arr=[$id];
                $company_ids_add=implode(',',$company_ids_arr);
                CustomerServiceAgent::where('id',$cust_id)->update([
                    'company_ids'=>$company_ids_add
                ]);*/
            }

            //生成默认管理员
            $password=Hash::make($input['mobile']);
            $user_data=[
                'name'=>$input['name'],
                'email'=>$input['email']?? '',
                'password'=>$password,
                'mobile'=>$input['mobile'],
                'role_id'=>1,
                'username'=>'admin',
                'company_id'=>$id,
                'status'=>1,
            ];
            User::create($user_data);
            //生成默认配置
            $set_data=[
                'id'=>$id,
                'site_title'=>$input['company_name'],
            ];
            Setting::add($set_data);
            if(in_array($input['model'],[2,3]))
            {
                if(!empty($input['bind_dispatch']))
                {
                    $balance_data=[
                        'company_uid'=>$id,
                        'company_id'=>$input['bind_dispatch'],
                        'balance'=>0,
                    ];
                    Balance::add($balance_data);
                    $data_mem=[
                        'nickname'=>$input['name'],
                        'mobile'=>$input['mobile'],
                        'password'=>$password,
                        'status'=>1,
                        'company_id'=>$input['bind_dispatch'],
                        'company_uid'=>$id,
                    ];
                    $info_mem=Member::create($data_mem);
                    $data_mem_info=[
                        'user_id'=>$info_mem->id,
                        'pay_type'=>2,
                        'company_id'=>$input['bind_dispatch'],
                    ];
                    MemberInfo::create($data_mem_info);
                    $data_mem_add=[
                        'user_id'=>$info_mem->id,
                        'name'=>$input['name'],
                        'mobile'=>$input['mobile'],
                        'company_id'=>$input['bind_dispatch'],
                    ];
                    MemberAddress::create($data_mem_add);
                }
                //插入商城配置
                $data_partner=[
                  'company_id'=>  $id,
                ];
                PartnerSetting::create($data_partner);
            }

            //判断是否需要排除菜单
            $company_type=$input['model'];
            if($open_reduction==0)
             {
                 $product_id=0;
                 switch ($company_type)
                 {
                     case 1://批发
                         $product_id=1;
                         break;
                     case 2://城配
                         $product_id=2;
                         break;
                     case 3://软件
                         $product_id=10;
                         break;
                 }
                 $menu_ids=Menu::whereIn('name',['系统还原','立即初始化'])
                     ->where('type',$product_id)->limit(2)->pluck('id')->toArray();
                 if($menu_ids)
                 {
                     $data_menu_pc=[];
                     foreach ($menu_ids as $menu_id)
                     {
                         $data_menu_pc[]=[
                           'menu_id'=>  $menu_id,
                           'product_id'=>  $product_id,
                           'company_id'=>  $id,
                         ];
                     }
                     DB::table('menu_auth')->insert($data_menu_pc);
                 }
             }
            DB::commit();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error(['-1',$exception->getMessage()]);
        }
        return $this->success();
    }

    //编辑公司
    public function editCompany(BaseRequest $request)
    {
        $input=$request->only('cust_id','product_ids','renewal_money','remark','id','company_name','company_fullname','name','mobile','email','address','start_time','end_time','domain_name','bind_dispatch','status','base_address','long_lati','commission_rate','open_reduction','salesman','contract','voucher');
        $rules=[
            'id'=>"required|exists:company,id",
            'company_name'=>'filled|string',
            'company_fullname'=>'filled|string',
            'name'=>'filled|string',
            'mobile'=>'filled|digits:11',
            'email'=>'email',
            'address'=>'filled|string',
            'status'=>'filled|in:0,1',
            'start_time'=>'filled|integer',
            'end_time'=>'filled|integer|gt:start_time',
            'domain_name'=>'filled|string',
//            'model'=>'filled|exists:company_type,id',
            'bind_dispatch'=>[
                'integer'
            ],
            'base_address'=>'filled|integer',
            'long_lati'=>'filled|string',
            'commission_rate'=>'required_unless:model,3|integer',
            'renewal_money'=>'required_if:model,3|numeric',
        ];
        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        if(isset($input['company_name']))
        {
            $company_name_old=Company::where('id',$id)->value('company_name');
            if($company_name_old!=$input['company_name'])
            {
                $res_co=Company::where('company_name',$input['company_name'])->count();
                if($res_co)
                {
                    return $this->error(['60001',config('errorcode.60001')]);
                }
            }
        }
        $model_info = $this->m_company->find($id);
        if(!empty($input['bind_dispatch']))
        {
            if($model_info->model==1)
            {
                return $this->error(['-1','客户类型不能更改']);
            }
            $where=[
                'id'=>$input['bind_dispatch'],
                'model'=>1,
            ];
            $res_co=Company::where($where)->count();
            if(!$res_co)
                return $this->error(['60002',config('errorcode.60002')]);
        }
        //判断域名唯一和格式
        if(isset($input['domain_name']))
        {
            $domain_name_old=Company::where('id',$id)->value('domain_name');
            if($domain_name_old!=$input['domain_name'])
            {
                $domain_arr=explode(',',$input['domain_name']);
                foreach ($domain_arr as $v)
                {
                    $info = Company::where('id','!=',$id)->whereRaw("FIND_IN_SET('".$v."',domain_name)")->count();
                    if($info)
                    {
                        return $this->error(['60003','域名已存在']);
                    }
                }
            }
        }
        if(isset($input['commission_rate']))
        {
            $input['commission_rate']=!empty($input['commission_rate'])?$input['commission_rate'].'‰':'';
        }
        DB::beginTransaction();
        try {
            //添加客服
            $cust_id=$input['cust_id']??0;
            //unset($input['cust_id']);
            if($cust_id)
            {
                /*$company_ids=CustomerServiceAgent::where('id',$cust_id)->value('company_ids');
                if($company_ids)
                {
                    $company_ids_arr=explode(',',$company_ids);
                    if(!in_array($id,$company_ids_arr))
                        $company_ids_arr[]=$id;
                }
                else
                    $company_ids_arr=[$id];
                $company_ids_add=implode(',',$company_ids_arr);
                CustomerServiceAgent::where('id',$cust_id)->update([
                    'company_ids'=>$company_ids_add
                ]);*/
            }
            if(!empty($input['bind_dispatch']) && in_array($model_info->model,[2,3]))
            {
                //判断是否存在过差额
                $is_balance=Balance::where('company_uid',$id)->where('company_id',$input['bind_dispatch'])->count();
                if(!$is_balance)
                {
                    $balance_data=[
                        'company_uid'=>$id,
                        'company_id'=>$input['bind_dispatch'],
                        'balance'=>0,
                    ];
                    Balance::add($balance_data);
                }
                //判断是否存在company_data
                $is_com_data=Member::where('company_uid',$id)->where('company_id',$input['bind_dispatch'])->count();
                $password=Hash::make($input['mobile']??'123456');
                if(!$is_com_data)
                {
                    $data_mem=[
                        'nickname'=>$input['name'],
                        'mobile'=>$input['mobile'],
                        'password'=>$password,
                        'status'=>1,
                        'company_id'=>$input['bind_dispatch'],
                        'company_uid'=>$id,
                    ];
                    $info_mem=Member::create($data_mem);
                    $data_mem_info=[
                        'user_id'=>$info_mem->id,
                        'pay_type'=>2,
                        'company_id'=>$input['bind_dispatch'],
                    ];
                    MemberInfo::create($data_mem_info);
                    $data_mem_add=[
                        'user_id'=>$info_mem->id,
                        'name'=>$input['name'],
                        'mobile'=>$input['mobile'],
                        'company_id'=>$input['bind_dispatch'],
                    ];
                    MemberAddress::create($data_mem_add);
                }
            }
            //赋值
            foreach ($input as $k=>$v){
                if(!is_array($v)){
                    $model_info->$k = $v;
                }
            }
            $perInfo = $model_info->getOriginal();//获取修改之前的字段
            //执行修改操作
            $model_info->save();
            $nextInfo = $model_info->getChanges();//获取修改之后的字段

            if (method_exists($this->m_company,'addLog')){
                if (!empty($nextInfo)){
                    $this->m_company->addLog($perInfo,$nextInfo,2);
                }
            }
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error(['-1',$exception->getMessage()]);
            return $this->error();
        }
    }

    //根据pid获取区域列表
    public function regionListByPid(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'pid'=>'required|integer|min:0',
        ];
        $validator = Validator::make($input, $rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $list=AdminRegion::getListByPid($input['pid']);
        $data=[
            'list'=>$list
        ];
        return $this->success($data);

    }

    //获取菜单类型，就是产品列表，不分页
    public function menuType(BaseRequest $request)
    {
        $data=CompanyType::get();
        return $this->success($data);
    }

    //根据类型获取菜单列表
    public function menuList(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'type'=>'required|exists:admin_product,id'
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $type=$input['type'];
        $list=Menu::getListByTypeAll($type);
        $data=[
          'list'=>  $list,
        ];
        return $this->success($data);
    }

    //新增菜单
    public function addMenu(BaseRequest $request)
    {
        $input=$request->only('name','type','pid','controller','route','icon','ordid','display','action','front_end_show');
        //过滤数据
        $rule=[
            'name'=>'required|string',
            'type'=>'required|exists:admin_product,id',
            'pid'=>'required|integer|min:0',
            'controller'=>'nullable|string',
            'route'=>'nullable|string',
            'action'=>'nullable|string',
            'icon'=>'nullable|string',
            'ordid'=>'integer|max:100',
            'display'=>'required|in:0,1',
            'front_end_show'=>'in:0,1',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        DB::beginTransaction();
        try {
            $m_info=Menu::create($input);
            if (method_exists($this->m_menu,'addLog')){
                $this->m_menu->addLog($m_info,[],1);
            }
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    //编辑菜单
    public function editMenu(BaseRequest $request)
    {
        $input=$request->only('id','name','pid','controller','route','icon','ordid','display','action','front_end_show');
        //过滤数据
        $rule=[
            'id'=>'required|integer|exists:menu,id',
            'name'=>'string',
            'pid'=>'integer|min:0',
            'controller'=>'nullable|string',
            'route'=>'nullable|string',
            'action'=>'nullable|string',
            'icon'=>'nullable|string',
            'ordid'=>'integer|max:100',
            'display'=>'in:0,1',
            'front_end_show'=>'in:0,1',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        unset($input['id']);
        DB::beginTransaction();
        try {
            $model_info = $this->m_menu->find($id);
            //赋值
            foreach ($input as $k=>$v){
                if(!is_array($v)){
                    $model_info->$k = $v;
                }
            }
            $perInfo = $model_info->getOriginal();//获取修改之前的字段
            //执行修改操作
            $model_info->save();
            $nextInfo = $model_info->getChanges();//获取修改之后的字段

            if (method_exists($this->m_menu,'addLog')){
                if (!empty($nextInfo)){
                    $this->m_menu->addLog($perInfo,$nextInfo,2);
                }
            }
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    //删除菜单
    public function deleteMenu(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'id'=>'required|integer|min:0|exists:menu,id',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        //判断是否还有子分类
        $is_son=Menu::where('pid',$id)->count();
        if($is_son)
        {
            return $this->error(['-1','请先删除该菜单下的子菜单']);
        }
        DB::beginTransaction();
        try{
            $m_info=Menu::find($id);
            if (method_exists($this->m_menu,'addLog')){
                $this->m_menu->addLog($m_info->toArray(),[],3,'delete');
            }
            Menu::where('id',$id)->delete();
            AdminAuth::where('menu_id',$id)->delete();
            //将客户资料，设置为-1
            Document::where('first_menu_id',$id)->orWhere('sec_menu_id',$id)->update(['first_menu_id'=>-1,'sec_menu_id'=>-1]);
            DB::commit();
            return $this->success();
        }catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    //获取菜单详情
    public function getMenuDetail(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'id'=>'required|exists:menu,id',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);

        $id=$input['id'];
        $info=Menu::getDetaiById($id)->toArray();
        //获取父级菜单
        $p_menu_list=Menu::getPMenuById($id);
        $active_pid=Menu::getPathById($id);
        $info['active_pid']=array_reverse($active_pid);
        $info['p_menu_list']=$p_menu_list;
        return $this->success($info);
    }

    //根据父id获取子菜单
    public function menuListByPid(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'pid'=>'required|integer|min:0',
            'type'=>'exists:admin_product,id',
        ];
        $validator = Validator::make($input, $rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $list=Menu::getListByPid($input);
        $data=[
            'list'=>$list
        ];
        return $this->success($data);
    }

    public function productByComId(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'company_id'=>'required|exists:company,id',
        ];
        $validator = Validator::make($input, $rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $company_id=$input['company_id'];
        $company_type=Company::where('id',$company_id)->value('model');
        $list=AdminProduct::whereRaw("FIND_IN_SET($company_type,company_type)")->select('id','name')->get();
        return $this->success(['list'=>$list]);
    }

    public function menuListExclude(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'company_id'=>[
                'required',
                Rule::exists('company','id')
            ],
            'product_id'=>[
                'required',
                Rule::exists('admin_product','id')
            ],
        ];
        $validator = Validator::make($input, $rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $company_id=$input['company_id'];
        $product_id=$input['product_id'];
        $list=Menu::getListByTypeAll($product_id);
        $yes = MenuAuth::where('company_id',$company_id)->where('product_id',$product_id)->pluck('menu_id');
        //是否选中
        foreach ($list as &$item)
        {
            if($yes->contains($item['id'])){
                $item['isSelect'] = true;
            }else{
                $item['isSelect'] = false;
            }
            foreach ($item['selfNext'] as &$val)
            {
                if($yes->contains($val['id'])){
                    $val['isSelect'] = true;
                }else{
                    $val['isSelect'] = false;
                }
                foreach ($val['selfNext'] as &$v)
                {
                    $v['selfNext'] = [];
                    if($yes->contains($v['id'])){
                        $v['isSelect'] = true;
                    }else{
                        $v['isSelect'] = false;
                    }
                }
            }
        }
        return  response()->json(['errcode'=>0,'data'=>['list'=>$list],'errmsg'=>'ok']);
    }

    //排除菜单
    public function excludeMenu(Request $request)
    {
        $input=$request->all();
        $rules=[
            'product_id'=>'required|exists:admin_product,id',
            'company_id'=>'required|exists:company,id',
            'ids'=>'nullable|array'
        ];
        $validator = Validator::make($input, $rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);

        $ids = $input['ids'];
        $product_id = $input['product_id'];
        $company_id = $input['company_id'];
        //组合新增数据
        $data = [];
        foreach ($ids as $val){
            $data[] = [
                'company_id' => $company_id,
                'product_id' => $product_id,
                'menu_id' => $val,
            ];
        }
        DB::beginTransaction();
        try {
            //先删除之前的记录
            MenuAuth::where('company_id', $company_id)->where('product_id',$product_id)->delete();
            //保存
            DB::table('menu_auth')->insert($data);

            DB::commit();
            return response()->json(['errcode'=>0,'errmsg'=>'ok']);
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error(['-1',$exception->getMessage()]);
        }
    }


    public function checkCompany(Request $request)
    {
        $id = $request->get('id');
        $info = Company::find($id);
        if ($info->audit) {
            return $this->error(['-1','该客户已审核']);
        }
        $info->audit = 1;
        $info->status = 1;
        if ($info->save()) {
            Company::addLog($info->toArray(),[],6,__FUNCTION__);
            return $this->success();
        } else {
            return $this->error();
        }
    }



    public function getOldSystem(Request $request)
    {
        $input=$request->all();
        $page = $input['page'] ?? 1;
        $per_page = $input['per_page'] ?? 20;
        $where[] = ['free_type','=',0];
        if(isset($input['company_name']))
        {
            $where[]=['company_name','like','%'.$input['company_name'].'%'];
        }
        if(isset($input['domain_name']))
        {
            $where[]=['domain_name','like','%'.$input['domain_name'].'%'];
        }
        if(isset($input['name']))
        {
            $where[]=['name','like','%'.$input['name'].'%'];
        }
        if(isset($input['mobile']))
        {
            $where[]=['mobile','like','%'.$input['mobile'].'%'];
        }
        if(isset($input['email']))
        {
            $where[]=['email','like','%'.$input['email'].'%'];
        }
        if(!empty($input['start_time']))
        {
            $start_time_arr=explode(',',$input['start_time']);
            if(count($start_time_arr)==2)
            {
                $time_1=$start_time_arr[0];
                $time_2=$start_time_arr[1];
                $where[]=['start_time','>=',$time_1];
                $where[]=['start_time','<=',$time_2+86400-1];
            }
        }
        if(!empty($input['end_time']))
        {
            $time_arr=explode(',',$input['end_time']);
            if(count($time_arr)==2)
            {
                $time_1=$time_arr[0];
                $time_2=$time_arr[1];
                $where[]=['end_time','>=',$time_1];
                $where[]=['end_time','<=',$time_2+86400-1];
            }
        }
        if (!isset($input['model'])) $input['model'] = 0;

        $select = $this->connection->table('company')->where($where);
        if($input['model'] == 1)
        {
            $select = $select->whereIn('version',[1,2,3,4]);
        } elseif ($input['model'] == 2) {
            $select = $select->whereIn('version',[5,6]);
        }
        if(!empty($input['status']))
        {
            if ($input['status'] == 1) {
                $select = $select->where('status',1)->where('end_time','>',time());
            } else {
                $select = $select->where(function ($query) {
                    $query->orWhere('status',0)->orWhere([['status','=',1],['end_time','<=',time()]]);
                });
            }
        }

        $list = $select->orderBy('created_at','desc')->get();
        if ($list->isEmpty()) {
            return $this->success(['list'=>[],'count'=>0]);
        }

        $data=$list->transform(function ($i,$k)
        {
            $time_now=time();
            $left_time=$i->end_time-$time_now;
            $left_time=$left_time<0?0:$left_time;
            $i->left_time=self::Sec2TimeStatic($left_time);
            if ($left_time == 0 && $i->status == 1) {
                $i->status = 0;
            }
            if (in_array($i->version, [1,2,3,4])) {
                $i->model_name = '软件';
            } else {
                $i->model_name = '城配';
            }
            return $i;
        });

        $count = count($data);
        $data = $data->chunk($per_page);
        $list = array_values($data[$page-1]->toarray());
        return $this->success(['list'=>$list,'count'=>$count]);
    }



}
